package application.encryption;

import javax.swing.JTextArea;

import dao.TxtFileWriter;

public class EncryptedInfo3 implements Encryption {

    public static final String CAESEA = "Caesar";
    private TxtFileWriter writer = new TxtFileWriter();
    private char[] passTable = new char[10 + 26 + 26];

    public EncryptedInfo3() {
        initPassTable();
    }

    @Override
    public void log(String lastNm, String firstNm, String code, JTextArea txt) {
        String lName = encryptName(lastNm);
        String fName = encryptName(firstNm);
        String codeStr = encryptCode(code);
        txt.append("Encrypted agent first name: " + fName + "\n");
        txt.append("Encrypted agent last name: " + lName + "\n");
        txt.append("Encrypted agent code: " + codeStr + "\n\n");

        writer.logMsg(CAESEA, lName, fName, codeStr);
        txt.append("Data has been saved into file " + CAESEA + ".txt" + "\n\n");
    }

    @Override
    public String encryptName(String inputStr) {
        char[] cipher = new char[inputStr.length()];
        for (int i = 0; i < inputStr.length(); ++i) {
            char ch = inputStr.charAt(i);
            cipher[i] = Character.isLetterOrDigit(ch) ? passTable[getIndex(ch)] : ch;
        }
        return new String(cipher);
    }

    @Override
    public String encryptCode(String code) {
        char[] cipher = new char[code.length()];
        for (int i = 0; i < code.length(); ++i) {
            char ch = code.charAt(i);
            cipher[i] = Character.isLetterOrDigit(ch) ? passTable[getIndex(ch)] : ch;
        }
        return new String(cipher);
    }

    private void initPassTable() {
        for (char i = '0'; i <= '9'; ++i) {
            passTable[getIndex(i)] = (char) ((i + 1 - '0') % 10 + '0');
        }

        for (char i = 'A'; i <= 'Z'; ++i) {
            passTable[getIndex(i)] = (char) ((i + 1 - 'A') % 26 + 'A');
            passTable[getIndex((char) (i + 32))] = (char) ((i + 32 + 1 - 'a') % 26 + 'a');
        }
    }

    private int getIndex(char ch) {
        if (Character.isDigit(ch)) {
            return ch - '0';
        }
        if (Character.isUpperCase(ch)) {
            return ch - 'A' + 10;
        }
        if (Character.isLowerCase(ch)) {
            return ch - 'a' + 10 + 26;
        }
        return -1;
    }
}
